package com.zky.gulimall.ware.service.impl;

import com.zky.common.constant.WareConstant;
import com.zky.gulimall.ware.entity.PurchaseDetailEntity;
import com.zky.gulimall.ware.service.PurchaseDetailService;
import com.zky.gulimall.ware.service.WareSkuService;
import com.zky.gulimall.ware.vo.MergePurchaseVo;
import com.zky.gulimall.ware.vo.PurchaseDownVo;
import com.zky.gulimall.ware.vo.PurchaseItemDownVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.ware.dao.PurchaseDao;
import com.zky.gulimall.ware.entity.PurchaseEntity;
import com.zky.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergePurchaseVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //todo 确认采购单是新建或已分配

        List<Long> items = vo.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new RuntimeException("合并采购单不能为空");
        }

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> entityList = items.stream().map(e -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(e);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNE.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(entityList);

        //变更更新时间字段

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void receivePurchase(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new RuntimeException("采购单不能为空");
        }
        //1 确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> entities = ids.stream().map(item -> {
            PurchaseEntity byId = this.getById(item);
            return byId;
        }).filter(e -> (e.getStatus() == WareConstant.PurchaseEnum.CREATED.getCode()
                || e.getStatus() == WareConstant.PurchaseEnum.ASSIGNE.getCode()))
                .map(f -> {
                    f.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
                    f.setUpdateTime(new Date());
                    return f;
                }).collect(Collectors.toList());

        //2 改变采购单状态
        this.updateBatchById(entities);

        //3 改变采购项状态
        entities.forEach(e->{
            List<PurchaseDetailEntity> list=purchaseDetailService.listDetailByPurchaseId(e.getId());
            List<PurchaseDetailEntity> entityList = list.stream().map(f -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(f.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(entityList);
        });
    }

    @Transactional
    @Override
    public void down(PurchaseDownVo vo) {
        //1改变采购相状态
        List<PurchaseItemDownVo> items = vo.getItems();
        if(CollectionUtils.isEmpty(items)){
            throw new RuntimeException("采购详情信息为空");
        }
        boolean flag=true;
        List<PurchaseDetailEntity> updates=new ArrayList<>();
        for (PurchaseItemDownVo item : items) {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            if(item.getStatus()==WareConstant.PurchaseDetailEnum.FAIL.getCode()){
                flag=false;
                entity.setStatus(item.getStatus());
            }else {
                entity.setStatus(WareConstant.PurchaseDetailEnum.FINISH.getCode());
                //查出采购单
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                if(byId!=null){
                    // 3将成功采购的入库
                    wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
                }
            }
            entity.setId(item.getItemId());
            updates.add(entity);
        }

        purchaseDetailService.updateBatchById(updates);

        //2 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(vo.getId());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseEnum.FINISH.getCode():WareConstant.PurchaseEnum.ERR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}